const app = getApp();
const api = require('../../utils/api.js');

Page({
  data: {
    imgBaseUrl: '',
    query: '',
    sortOptions: ['综合排序', '书名 A→Z', '书名 Z→A', '作者 A→Z'],
    sortIndex: 0,
    viewMode: 'grid', // grid | list
    allBooks: [],
    books: [],
    pageIndex: 1,
    pageSize: 12,
    hasMore: true,
    loading: false,
    refreshing: false,
    drawer: { show: false, data: { id: null, title: '', cover: '', author: '', desc: '' } }
  },

  onLoad() {
    this.setData({ imgBaseUrl: api.ENV.imgBaseUrl || '' });
    this.fetchBooks(true);
  },

  // 构造或获取书籍数据
  fetchBooks(reset = false) {
    if (this.data.loading) return;
    this.setData({ loading: true });

    // 示例数据，可替换为接口请求
    const list = [
      { id: 1, title: '校史', cover: 'book-cover1.png', author: '校史编委会', desc: '系统回顾学校发展历程' },
      { id: 2, title: '名人传记', cover: 'book-cover2.png', author: '佚名', desc: '记述历届名师与校友事迹' },
      { id: 3, title: '学术论文集', cover: 'book-cover1.png', author: '学术处', desc: '汇编高水平学术成果' },
      { id: 4, title: '校园文化', cover: 'book-cover2.png', author: '宣传部', desc: '展现独特校园文化底蕴' },
      { id: 5, title: '教学成果', cover: 'book-cover1.png', author: '教务处', desc: '优秀教学成果集' },
      { id: 6, title: '校友风采', cover: 'book-cover2.png', author: '校友会', desc: '校友故事与成就' },
      { id: 7, title: '科研成果', cover: 'book-cover1.png', author: '科研院', desc: '科研项目与成果集萃' },
      { id: 8, title: '校园建设', cover: 'book-cover2.png', author: '基建处', desc: '建设与规划纪实' },
      { id: 9, title: '教育理念', cover: 'book-cover1.png', author: '教育研究所', desc: '教育思想与理念' },
      { id: 10, title: '发展规划', cover: 'book-cover2.png', author: '发展规划处', desc: '未来发展蓝图' },
      { id: 11, title: '德育教育', cover: 'book-cover1.png', author: '学工部', desc: '立德树人实践' },
      { id: 12, title: '艺术与美育', cover: 'book-cover2.png', author: '美育中心', desc: '美育课程与作品' }
    ];

    if (reset) {
      this.setData({ allBooks: list, pageIndex: 1, books: [], hasMore: true });
    } else {
      this.setData({ allBooks: list });
    }
    this.applyQueryAndSort(true);
    this.setData({ loading: false, refreshing: false });
  },

  applyQueryAndSort(resetPage = false) {
    const q = (this.data.query || '').trim().toLowerCase();
    let arr = [...this.data.allBooks];
    if (q) arr = arr.filter(it => (it.title||'').toLowerCase().includes(q) || (it.author||'').toLowerCase().includes(q) || (it.desc||'').toLowerCase().includes(q));

    switch (this.data.sortIndex) {
      case 1:
        arr.sort((a,b)=> (a.title||'').localeCompare(b.title||''));
        break;
      case 2:
        arr.sort((a,b)=> (b.title||'').localeCompare(a.title||''));
        break;
      case 3:
        arr.sort((a,b)=> (a.author||'').localeCompare(b.author||''));
        break;
      default:
        // 综合：保持原序
        break;
    }

    let pageIndex = this.data.pageIndex;
    if (resetPage) pageIndex = 1;
    const start = (pageIndex - 1) * this.data.pageSize;
    const next = arr.slice(start, start + this.data.pageSize);
    const hasMore = start + this.data.pageSize < arr.length;

    this.setData({
      books: pageIndex === 1 ? next : this.data.books.concat(next),
      hasMore,
      pageIndex
    });
  },

  onInput(e) { this.setData({ query: e.detail.value || '' }); },
  onSearch() { this.setData({ pageIndex: 1, books: [], hasMore: true }); this.applyQueryAndSort(true); },
  onSortChange(e) { const idx = Number(e.detail.value)||0; this.setData({ sortIndex: idx, pageIndex:1, books:[], hasMore:true }); this.applyQueryAndSort(true); },
  toggleView() { this.setData({ viewMode: this.data.viewMode === 'grid' ? 'list' : 'grid' }); },

  onRefresh() { this.setData({ refreshing: true }); this.fetchBooks(true); },
  onReachBottom() { if (!this.data.hasMore || this.data.loading) return; this.setData({ pageIndex: this.data.pageIndex + 1 }); this.applyQueryAndSort(false); },

  openDetail(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.books[idx];
    if (!item) return;
    this.setData({ drawer: { show: true, data: item } });
  },
  closeDrawer() { this.setData({ drawer: { show: false, data: { id: null, title: '', cover: '', author: '', desc: '' } } }); },

  readOnline() {
    const book = this.data.drawer.data;
    if (!book || !book.id) { wx.showToast({ title: '未选择书籍', icon: 'none' }); return; }
    // 如有阅读器页面，可跳转；否则提示
    try {
      wx.navigateTo({ url: `/pages/bookreader/bookreader?id=${book.id}` });
    } catch (e) {
      wx.showToast({ title: '阅读器开发中', icon: 'none' });
    }
  },
  download() { wx.showToast({ title: '开始下载（示例）', icon: 'none' }); }
});